import express from "express";
import { getDate } from "./lib/time.mjs";
import dbTool from "./lib/DbUtil.mjs";
const app = express();
let _port = 10915;
/**
 * @flutter /flutter/setcmd
 * - 服务器从 query 获取信号信息 val_1 2 3
 * - 并设置该信号为下一条cmd
 */
app.get("/flutter/setcmd", (req, res) =>
{
  let qs = req.query;
  let signal = {
    val_1: qs.val_1 || 0,
    val_2: qs.val_2 || 0,
    val_3: qs.val_3 || 0,
  };
  dbTool.insert(
    "insert into `cmd`(val_1,val_2,val_3,cmd_time) values(?,?,?,?)",
    [signal.val_1, signal.val_2, signal.val_3, getDate(true)],
    (res, fields) =>
    {
      dbTool.query("select max(cmd_id) m from `cmd`", (data) =>
      {
        console.log("插入成功 cmd_id is " + data[0].m);
      });
    }
  );
  console.log("————————————Respond———flutter_setcmd—————————————————————————");
  // console.log("query  is " + JSON.stringify(query));
  console.log("signal is " + JSON.stringify(signal));
  console.log("——————————————————Over———————————————————————————————————————");
  res.send("/flutter/setcmd");
});
/**
 * @flutter /flutter/getshow
 * - 服务器应返回
 * - 最近收到的信息
 * - 即 表dones 的最近信息
 */
app.get("/flutter/getshow", (req, res) =>
{
  dbTool.query(
    "SELECT done_id, val_1, val_2, val_3, done_time FROM dones ORDER BY done_id DESC LIMIT 0,10",
    (data) =>
    {
      res.send(data);
      // for (let i = 0; i < data.length; i++) {
      // res.write(Buffer.from(data[i]));
      // res.write(JSON.stringify(data[i]));
      // res.write("<br/>");
      // console.log();
      // }
    }
  );
});

/**
 * @exp32 /esp32/getcmd
 * - 服务器应返回
 * - 从cmd表中查询到的信息
 */
app.get("/esp32/getcmd", (req, res) =>
{
  console.log("————————————Respond———esp32_getcmd—————————————————————————");
  dbTool.query(
    "select cmd_id,val_1,val_2,val_3 from `cmd` limit 0,1",
    (data) =>
    {
      console.log("查得 cmd：" + JSON.stringify(data[0]));
      res.json(data[0]);
    }
  );
  console.log("——————————————————Over———————————————————————————————————————");
});

/**
 * @exp32 /esp32/finishcmd
 * - 服务器明白esp32完成了cmd任务
 * - 服务器更新cmd表（delete）
 */
app.get("/esp32/finishcmd", (req, res) =>
{
  let cmd_id = req.query.id || -1;
  if (cmd_id == -1)
  {
    console.error("异常的cmd_id: " + cmd_id);
    res.end();
  } else
  {
    dbTool.del("delete from `cmd` where cmd_id=?", [cmd_id], (result) =>
    {
      if (result.affectedRows > 0)
      {
        console.log("删除成功：" + cmd_id);
        res.send("删除成功：" + cmd_id);
      } else
      {
        res.send("Unexpected ERROR");
      }
    });
  }
});

/**
 * @exp32 /esp32/hadsig
 * - 服务器从 query 中获取 val_1 2 3
 * - esp32收到了一个信号，于是报告给服务器
 */
app.get("/esp32/hadsig", (req, res) =>
{
  // console.log("————————————this is 81————————————");
  let qs = req.query;
  let s = {
    val_1: qs.val_1,
    val_2: qs.val_2,
    val_3: qs.val_3,
    time: getDate(true),
  };
  dbTool.insert(
    "insert into `dones`(val_1,val_2,val_3,done_time) values(?,?,?,?)",
    [s.val_1, s.val_2, s.val_3, s.time],
    () =>
    {
      let sql =
        "select max(done_id) id from `dones` where done_time='" + s.time + "'";
      dbTool.query(sql, (data) =>
      {
        // console.log(sql);
        console.log("esp32 收到信号：");
        console.log(s);
        console.log("dones 新增一条数据成功  id: ", data[0].id);
        res.send("dones 新增一条数据成功  id: ", data[0].id);
        // console.log(res.status());
        console.log("\n\n");
      });
    }
  );
  // console.log(qs);
});
/**
 * @lib /lib
 * 对 keys 表进行相应的操作
 */
app.get("/lib/:act", (req, res) => { });
app.get("*", (req, res) =>
{
  console.log("任意门被访问了");
  res.send("欢迎来到任意门");
});
var server = app.listen(_port, function ()
{
  // var host = server.address().address;
  // var port = server.address().port;
  // console.log(server.address());
  // console.log("app    应用实例，访问地址为 http://%s:%s", host, port);
  // console.log("\n");
});
server.close();
server.listen(_port, "0.0.0.0", () =>
{
  var host = server.address().address;
  var port = server.address().port;
  console.log(server.address());
  console.log("Server 应用实例，访问地址为 http://%s:%s", host, port);
  console.log("\n");
});
